package com.yeskery.nut.script.function.extend;

import com.yeskery.nut.core.NutException;
import com.yeskery.nut.script.function.Function;
import com.yeskery.nut.util.StringUtils;

import java.util.concurrent.ThreadLocalRandom;
import java.util.logging.Logger;

/**
 * 手机号函数
 * @author sprout
 * 2022-05-20 16:53
 */
public class PhoneFunction implements Function {

    /** 日志对象 */
    private final static Logger logger = Logger.getLogger(PhoneFunction.class.getName());

    /** 中国移动 */
    public static final String[] CHINA_MOBILE = {
            "134", "135", "136", "137", "138", "139", "150", "151", "152", "157", "158", "159",
            "182", "183", "184", "187", "188", "178", "147", "172", "198"
    };
     /** 中国联通 */
    public static final String[] CHINA_UNICOM = {
            "130", "131", "132", "145", "155", "156", "166", "171", "175", "176", "185", "186", "166"
    };
     /** 中国电信 */
    public static final String[] CHINA_TELECOME = {
            "133", "149", "153", "173", "177", "180", "181", "189", "199"
    };

    @Override
    public String getName() {
        return "phoneGenerator";
    }

    @Override
    public String apply(String content) throws Exception {
        if (StringUtils.isEmpty(content)) {
            return createMobile(ThreadLocalRandom.current().nextInt(3));
        }
        try {
            int op = Integer.parseInt(content);
            if (op < 0) {
                op = 0;
            } else if (op > 2) {
                op = 2;
            }
            return createMobile(op);
        } catch (Exception e) {
            logger.info("Function [" + getName() + "] Format Number Fail. At Expression: [" + content + "]");
        }

        return createMobile(ThreadLocalRandom.current().nextInt(3));
    }

    /**
     * 生成手机号
     * @param op 0 移动 1 联通 2 电信
     * @return 生成的手机号
     */
    public static String createMobile(int op) {
        StringBuilder sb = new StringBuilder();
        String mobile01;
        int temp;
        switch (op) {
            case 0:
                mobile01 = CHINA_MOBILE[ThreadLocalRandom.current().nextInt(CHINA_MOBILE.length)];
                break;
            case 1:
                mobile01 = CHINA_UNICOM[ThreadLocalRandom.current().nextInt(CHINA_UNICOM.length)];
                break;
            case 2:
                mobile01 = CHINA_TELECOME[ThreadLocalRandom.current().nextInt(CHINA_TELECOME.length)];
                break;
            default:
                throw new NutException("Wrong op [" + op + "]");
        }
        if (mobile01.length() > 3) {
            return mobile01;
        }
        sb.append(mobile01);
        //生成手机号后8位
        for (int i = 0; i < 8; i++) {
            temp = ThreadLocalRandom.current().nextInt(10);
            sb.append(temp);
        }
        return sb.toString();
    }
}
